import { AppConfig } from '../../shared/types'
import { DEFAULT_APP_CONFIG } from '../../shared/constants'
import { logger } from '@roasmax/logger'
import { useQuery, useQueryFactory } from '../storage/data-source'

export class ConfigManager {
  private config: AppConfig = DEFAULT_APP_CONFIG

  constructor() { }

  /**
   * 初始化配置管理器
   */
  async initialize(): Promise<void> {
    await this.loadConfig()
  }

  /**
   * 从数据库加载配置
   */
  private async loadConfig(): Promise<void> {
    try {
      const rows = await useQuery<any[]>('SELECT key, value FROM config', [])

      if (rows.length === 0) {
        // 首次运行，保存默认配置
        await this.saveConfigToDatabase()
        logger.info('首次运行，已保存默认配置')
        return
      }

      // 重建配置对象
      const savedConfig: any = {}
      for (const row of rows) {
        try {
          savedConfig[row.key] = JSON.parse(row.value)
        } catch (error) {
          logger.error(`解析配置项失败: ${row.key}`, error)
        }
      }

      // 合并默认配置和保存的配置
      this.config = this.mergeConfigs(DEFAULT_APP_CONFIG, savedConfig)
      logger.info('配置加载完成')
    } catch (error) {
      logger.error('加载配置失败，使用默认配置:', error)
      this.config = DEFAULT_APP_CONFIG
    }
  }

  /**
   * 深度合并配置对象
   */
  private mergeConfigs(defaultConfig: AppConfig, savedConfig: any): AppConfig {
    return {
      crawler: { ...defaultConfig.crawler, ...savedConfig.crawler },
      proxy: { ...defaultConfig.proxy, ...savedConfig.proxy },
      storage: { ...defaultConfig.storage, ...savedConfig.storage },
      logging: { ...defaultConfig.logging, ...savedConfig.logging }
    }
  }

  /**
   * 将配置保存到数据库
   */
  private async saveConfigToDatabase(): Promise<void> {
    try {
      const queryFactory = useQueryFactory(`
        INSERT OR REPLACE INTO config (id, key, value, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?)
      `)

      const now = Date.now()
      await queryFactory('config_crawler', 'crawler', JSON.stringify(this.config.crawler), now, now)
      await queryFactory('config_proxy', 'proxy', JSON.stringify(this.config.proxy), now, now)
      await queryFactory('config_storage', 'storage', JSON.stringify(this.config.storage), now, now)
      await queryFactory('config_logging', 'logging', JSON.stringify(this.config.logging), now, now)

      logger.info('配置已保存到数据库')
    } catch (error) {
      logger.error('保存配置到数据库失败:', error)
      throw error
    }
  }

  /**
   * 获取应用配置
   */
  async getConfig(): Promise<AppConfig> {
    logger.info('获取应用配置')
    return { ...this.config }
  }

  /**
   * 更新应用配置
   */
  async updateConfig(configUpdate: Partial<AppConfig>): Promise<void> {
    logger.info('更新应用配置', configUpdate)

    // 深度合并配置
    this.config = {
      ...this.config,
      ...configUpdate,
      crawler: { ...this.config.crawler, ...configUpdate.crawler },
      proxy: { ...this.config.proxy, ...configUpdate.proxy },
      storage: { ...this.config.storage, ...configUpdate.storage },
      logging: { ...this.config.logging, ...configUpdate.logging }
    }

    // 保存到数据库
    await this.saveConfigToDatabase()
    logger.info('应用配置更新完成')
  }

  /**
   * 重置配置为默认值
   */
  async resetConfig(): Promise<void> {
    logger.info('重置配置为默认值')
    this.config = { ...DEFAULT_APP_CONFIG }
    await this.saveConfigToDatabase()
    logger.info('配置重置完成')
  }

  /**
   * 获取特定配置项
   */
  getConfigItem<K extends keyof AppConfig>(key: K): AppConfig[K] {
    return this.config[key]
  }

  /**
   * 更新特定配置项
   */
  async updateConfigItem<K extends keyof AppConfig>(
    key: K,
    value: Partial<AppConfig[K]>
  ): Promise<void> {
    logger.info(`更新配置项: ${key}`, value)

    this.config[key] = { ...this.config[key], ...value }
    await this.saveConfigToDatabase()

    logger.info(`配置项 ${key} 更新完成`)
  }
}
